package com.itdata.common;

import java.io.IOException;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Properties;

import javax.crypto.Cipher;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

public class RsaCryptoUtil {
	public static final String PUB_KEY = "pub_key";
	public static final String PRIV_KEY = "priv_key";
	public static Key loadKey(String type)
            throws NoSuchAlgorithmException,
            InvalidKeySpecException, IOException {
		InputStream is = ClassLoader.getSystemResourceAsStream("application.properties");
		if(is==null){
			is = RsaCryptoUtil.class.getClassLoader().getResourceAsStream("/application.properties");
		}
        Properties config = new Properties();
        config.load(is);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());

        if (PRIV_KEY.equals(type)) {
            // privateKey
            String privateKeyValue = config.getProperty(PRIV_KEY);
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
            		Base64.decode(privateKeyValue));
            PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
            return privateKey;

        } else {
            // publicKey
            String privateKeyValue = config.getProperty(PUB_KEY);
            X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(
                    Base64.decode(privateKeyValue));
            PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
            return publicKey;
        }
    }
	
	public static String decrypt(RSAPrivateKey privateKey, String cipherText) {
		byte[] raw = Base64.decode(cipherText);
        if (privateKey != null) {
            try {
                Cipher cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                return new String(cipher.doFinal(raw));
            } catch (Exception e) {
                throw new RuntimeException("解密失败！");
            }
        }
        return null;
    }
	
	
}
